package com.example.android.ouactivity;
/*
 * Created by kelion on 2016/11/14.
 */


import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.android.ouactivity.adapter.RecyclerViewAdapter;
import com.example.android.ouactivity.model.News;
import com.example.android.ouactivity.utils.CustomHttp;
import com.example.android.ouactivity.utils.HttpUtils;
import com.example.android.ouactivity.utils.SnackbarUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import static android.support.v7.widget.RecyclerView.SCROLL_STATE_IDLE;


//onAttach -> oncreate -> oncreateView -> onActivityCreate -> onstart
public class MainFragment extends Fragment
        implements  SwipeRefreshLayout.OnRefreshListener {
    private View mView;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private RecyclerView mRecyclerView;
    private RecyclerViewAdapter mRecyclerViewAdapter;
    private String NEWS_URL;
    List<News> newsList = new ArrayList<>();
    public MainFragment(String url){
        this.NEWS_URL = url;
    }
    //是否加载
    boolean isLoadMore = false;

    private int mStart;
    private int mEnd;
    public static String[]URLS;
    private boolean mFirstIn;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.refresh_recycler, container, false);

        new NewAsyncTask().execute(NEWS_URL);
        initView();

        return mView;
    }


    public void initView(){

        mSwipeRefreshLayout = (SwipeRefreshLayout) mView.findViewById(R.id.id_swiperefreshlayout);
        mRecyclerView = (RecyclerView) mView.findViewById(R.id.id_recyclerview);
        // 刷新时，指示器旋转后变化的颜色
        mSwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_purple, android.R.color.holo_blue_bright, android.R.color.holo_orange_light, android.R.color.holo_red_light);
        //监听下拉刷新SwipeRefreshLayout.OnRefreshListener
        mSwipeRefreshLayout.setOnRefreshListener(this);
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {




        super.onActivityCreated(savedInstanceState);

        //模拟加载更多
        mRecyclerView.addOnScrollListener(new RecyclerView.
                OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                RecyclerView.LayoutManager mLayoutManager = recyclerView.getLayoutManager();

                //最后一个可见子项 的标志数
                int lastVisibleItem = ((LinearLayoutManager) mLayoutManager).findLastVisibleItemPosition();
                //第一个可见子项  的标志数
                int firstVisibleItem = ((LinearLayoutManager) mLayoutManager).findFirstVisibleItemPosition();
                //当前屏幕所看到的子项个数
                int visibleItemCount = mLayoutManager.getChildCount();
                //当前RecyclerView的所有子项个数
                int totalItemCount = mLayoutManager.getItemCount();

                //起始可见项
                mStart = firstVisibleItem;
                //末尾可见项
                mEnd = mStart +visibleItemCount;

                //最后一项显示且是下滑的时候调用加载
                if (lastVisibleItem >= totalItemCount - 1 && dy > 0) {
                    if (isLoadMore) {
                        return;
                    }
                    final String id = String.valueOf(newsList.get(newsList.size()-1).getId());
                    isLoadMore = true;
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Handler handler = new Handler(){
                                @Override
                                public void handleMessage(Message msg) {
                                    super.handleMessage(msg);
                                    String result = msg.obj.toString();
                                    Gson gson = new Gson();
                                    List<News> list = gson.fromJson(result,new TypeToken<List<News>>(){}.getType());
                                    if(list!=null){
                                        for (int i = 0;i<list.size();i++) {
                                            newsList.add(list.get(i));
                                        }
                                        mSwipeRefreshLayout.setRefreshing(false);
                                        mRecyclerViewAdapter.notifyDataSetChanged();
                                        isLoadMore = false;
                                    }else {
                                        Toast.makeText(getContext(),"没有数据了",Toast.LENGTH_SHORT).show();
                                    }
                                }
                            };
                            HttpUtils http = new HttpUtils();
                            http.getNewsJSON("http://www.chqing.cn/refresh?id="+id,handler);
                        }
                    }, 2000);
                }
            }


            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState){
                //处于停止状态
                if (newState != SCROLL_STATE_IDLE){

                    //加载可见项
                }else {
                    //停止加载

                }

            }

        });

    }



    // 下拉刷新时模拟数据的变化
    //@Override
    public void onRefresh() {
        if(newsList.size() == 0){
            Log.i("无数据","数据未加载");
            Toast.makeText(getContext(), "连接失败",
                    Toast.LENGTH_SHORT).show();
            mSwipeRefreshLayout.setRefreshing(false);
            return ;
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                final String id = String.valueOf(newsList.get(0).getId());
                Handler handler = new Handler(){
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        String result = msg.obj.toString();
                        Gson gson = new Gson();
                        List<News> list = gson.fromJson(result,new TypeToken<List<News>>(){}.getType());
                        if(list!=null){
                            for (int i = 0;i<list.size();i++) {
                                newsList.add(0,list.get(i));
                                mRecyclerViewAdapter.notifyDataSetChanged();
                                mSwipeRefreshLayout.setRefreshing(false);
                            }
                        }else {
                            Toast.makeText(getContext(),"已是最新数据",Toast.LENGTH_SHORT).show();
                        }
                    }
                };
                HttpUtils http = new HttpUtils();
                http.getNewsJSON("http://www.chqing.cn/refresh?type=top&id="+id,handler);

//
            }
        }, 1000);

        mSwipeRefreshLayout.setRefreshing(false);
    }


    /**
     * 实现网络的异步访问
     */
    class NewAsyncTask extends AsyncTask<String, Void, List<News>> implements RecyclerViewAdapter.OnItemClickListener {

        @Override
        protected void onPostExecute(List<News> newsBeams)
        {
            RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity(),
                    LinearLayoutManager.VERTICAL, false);

            mRecyclerViewAdapter = new RecyclerViewAdapter(getActivity(), newsList);
            mRecyclerViewAdapter.setOnItemClickListener(this);
            mRecyclerView.setAdapter(mRecyclerViewAdapter);

            mRecyclerView.setLayoutManager(mLayoutManager);

        }

        @Override
        protected List<News> doInBackground(String... params)
        {
            try {
                return getJsonData(params[0]);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        /**
         * 从 URL 中获取数据
         */
        private List<News> getJsonData(String url) throws JSONException {
            try
            {
                String jsonString = readStream(new URL(url).openStream());
                Gson gson = new Gson();
                newsList = gson.fromJson(jsonString,new TypeToken<List<News>>(){}.getType());
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
            return newsList;
        }


        /**
         * 从 inpustStream 获取的信息
         */
        private String readStream(InputStream is)
        {
            InputStreamReader isr;
            String result = "";
            try
            {
                isr = new InputStreamReader(is, "utf-8");
                BufferedReader br = new BufferedReader(isr);
                String line;
                while((line = br.readLine()) != null)
                {
                    result += line;
                }
            } catch(IOException e)
            {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        public void onItemClick(View view, int position) {
            Intent con = new Intent(view.getContext(), ContentActivity.class);
            News news = newsList.get(position);
            Bundle bundle = new Bundle();
            bundle.putString("id",String.valueOf(news.getId()));
            con.putExtras(bundle);
            startActivity(con);
        }

        @Override
        public void onItemLongClick(View view, int position) {
            SnackbarUtil.show(mRecyclerView, getString(R.string.item_longclicked), 0);
        }

    }

}
